package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.Dr_List;
import com.wehealth.Dr_Free;
import com.wehealth.adapter.Adapter_Health_search_food_item;
import com.wehealth.adapter.Adapter_Health_search_item;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.dm.DM_HealthSearchFoodAndSportClassify;
import com.wehealth.dm.DM_HealthSearchList;
import com.wehealth.dm.QuestionData;
import com.wehealth.util.GetUrl;

@SuppressLint("ValidFragment")
public class Health_search_foodAndSport_list extends Fragment {
	
	private MainActivity context;
	
	private List<DM_HealthSearchList> mFoodList;
	private ListView  mFoodListView;
	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	private DM_HealthSearchFoodAndSportClassify  mFood;
	private int classify;
	   private static final int DISEACE = 1;
	   private static final int FOOD = 2;
	   private static final int SPORT =3;
	   private    String urlAPI ;
	   private ProgressBar mProgress;
	
	public  Health_search_foodAndSport_list( )
	{
	
	}
	
	public Health_search_foodAndSport_list(DM_HealthSearchFoodAndSportClassify mFood,int screen){
	   this.mFood = mFood;
	   classify = screen;
	 }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.health_search_list, null);
	}
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		MainActivity activity = (MainActivity)getActivity();
		context = activity; 
		
		mProgress = (ProgressBar)context.findViewById(R.id.progressbar);
		mProgress.setVisibility(View.VISIBLE);
		
		TextView titleTx =(TextView)context.findViewById(R.id.health_search_list_title);
		String title=null;
		title = mFood.getTitle();
		titleTx.setText(title);
		
		MobclickAgent.openActivityDurationTrack(false);
		Button bBack = (Button) activity.findViewById(R.id.b_back);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
                    MainActivity activity = (MainActivity) getActivity();                       
                    activity.switchContentHome();
				}
			});
		 
		 mFoodListView = (ListView)context.findViewById(R.id.health_search_food_list);
		 ConnService();
	}

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Health_search_food_list"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Health_search_food_list"); 
    }
	

    private void  ConnService(){
        
        //读取接口数据
        new Thread(){
            @Override
            public void run(){
            //你要执行的方法
                try {
                    InitThisView();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            //执行完毕后给handler发送一个空消息
            handler.sendEmptyMessage(0);
            }
            }.start();
    }
    
    private void  InitThisView() throws IOException
    {
    	HttpPost httpRequest = null;
        List <NameValuePair> params = new ArrayList <NameValuePair>();
        Log.d("SIMMON","InitThisView");
	   switch (classify) {
	   	case FOOD:
	   		urlAPI = GetUrl.GetHealthSearch_FoodSortID_Url();
	   		httpRequest= new HttpPost(urlAPI);
	        
	         params.add(new BasicNameValuePair("sortID",mFood.getSortID()));
	   		break;
	   	case SPORT:
	   		urlAPI = GetUrl.GetHealthSearch_SportLevelList_Url();
	      httpRequest= new HttpPost(urlAPI);
	      params.add(new BasicNameValuePair("levelID",mFood.getID()));
	   		break;
	   	default:
	   		break;
	   	}

         try
         {
             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
             HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);       
             if(httpResponse.getStatusLine().getStatusCode() == 200)
             {  
                 Log.d("SIMMON","InitThisView  1");
                 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
                 Log.d("SIMMON","InitThisView  JSONResult="+JSONResult);
             }       
         }
         catch(Exception e)
         {      
            
         }

    }
    
    
    
    //定义Handler对象
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg){
        super.handleMessage(msg);
        //处理UI
        if(JSONResult ==null){
            mProgress.setVisibility(View.GONE);
            openDialog(NET_ERROR);
        }else{
            BindList(JSONResult);
            JSONResult =null;
        }
        }
    };
    

    
    //将JSON数据绑定到LISTVIEW
    private void BindList(String strJSON){
       try{
           Log.d("SIMMON","BindList  1");
               mFoodList = new ArrayList<DM_HealthSearchList>();
                JSONObject jsonObject = new JSONObject(strJSON); 
                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
                for(int i=0; i<aNews.length(); i++)
                    {
                    DM_HealthSearchList  mFood= new DM_HealthSearchList();
                    mFood.setID(aNews.getJSONObject(i).getString("ID"));
                    mFood.setTitle(aNews.getJSONObject(i).getString("name"));
                    mFood.setenergy(aNews.getJSONObject(i).getString("energy"));
                    Log.d("SIMMON"," NAME="+aNews.getJSONObject(i).getString("name"));
                    mFoodList.add(mFood);
                }
                Log.d("SIMMON","BindList aNews.length()= "+aNews.length());
                updateListViewData(mFoodList);
            }
            catch(JSONException ex)
            {
                    Log.e("JSON Error: ", ex.toString()); 
            }
    }
    
    
    private  void updateListViewData(List<DM_HealthSearchList> datas ){

        mProgress.setVisibility(View.GONE);
        Adapter_Health_search_food_item adapter = new Adapter_Health_search_food_item(context,datas);
        mFoodListView.setAdapter(adapter);
        mFoodListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int pos, long pos2) {
      
                switch (classify) {
                case FOOD:
                    Health_search_food_descrip  mNextScreen = new Health_search_food_descrip(mFoodList.get(pos));
                    context.switchContent(mNextScreen);
                    break;
                case SPORT:
                    Health_search_sport_descrip  mNextScreen2 = new Health_search_sport_descrip(mFoodList.get(pos));
                    context.switchContent(mNextScreen2);
                    break;
                default:
                    break;
                }

            }
        });
        
    }
    
    
    
    private void openDialog(final int result){
        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
        builder.setIcon(null);
        String login_result =null;
    
        switch (result) {
        case NET_ERROR:
            login_result = getString(R.string.net_connet_fail);
            break;
            }
         TextView textview = new TextView(context);
         textview.setText(login_result);
         textview.setTextColor(Color.BLACK);
         textview.setTextSize(18);

         textview.setGravity(Gravity.CENTER);
         builder.setView(textview);
         
         
         builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
             @Override
             public void onClick(DialogInterface arg0, int arg1) {
                 // TODO Auto-generated method stub

             }
             
         });
         builder.create().show();
         
     }  
    

}
